<template>
  <div class="login-container">

    <div class="slider">

      <div :class="active === 1? 'form' : 'form hidden'">
        <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            label-width="auto"
        >
          <div class="title">欢迎<b>回来</b></div>
          <div class="subtitle">登录你的账户</div>
          <el-form-item label="账号" prop="username">
            <el-input v-model="loginForm.username" placeholder="请输入账号" type="text" autocomplete="off" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="loginForm.password" placeholder="请输入密码" type="password" autocomplete="off"/>
          </el-form-item>
          <button @click="submitForm">登录</button>
        </el-form>
      </div>
      <div :class="active === 2? 'form' : 'form hidden'">

        <el-form
            ref="registerFormRef"
            :model="merchantLoginForm"
            :rules="registerRules"
            label-width="80px"
        >
          <div class="you1">
            <div class="title">欢迎<b>注册</b></div>
            <div class="subtitle">注册你的账户</div>
          </div>
          <div class="you">
            <el-form-item  prop="mname" label="用户名">
              <el-input v-model="merchantLoginForm.mname" type="text" placeholder="用户名" style="height: 30px" maxlength="15"/>
            </el-form-item>
            <el-form-item  prop="mpassword" label="密码">
              <el-input v-model="merchantLoginForm.mpassword" type="text" placeholder="密码" style="height: 30px"/>
            </el-form-item>
            <el-form-item  prop="confirmPass" >
              <el-input v-model="merchantLoginForm.confirmPass" type="text" placeholder="再次输入密码" style="height: 30px"/>
            </el-form-item>
            <el-form-item  prop="mphone" label="手机号" >
              <el-input
                  v-model="merchantLoginForm.mphone"
                  type="text"
                  placeholder="手机号"
                  maxlength="11"
                  style="height: 30px" show-word-limit
              ></el-input>
            </el-form-item>
            <!-- 食堂下拉框 -->
            <el-form-item prop="canteen" label="食堂">
              <el-select v-model="merchantLoginForm.canteen" placeholder="请选择食堂">
                <el-option label="第一食堂" value="第一食堂"></el-option>
                <el-option label="第二食堂" value="第二食堂"></el-option>
                <el-option label="第三食堂" value="第三食堂"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="mrange" label="类型">
              <el-select v-model="merchantLoginForm.mrange" placeholder="请选择类型">
                <el-option label="家常菜" value="家常菜"></el-option>
                <el-option label="面食" value="面食"></el-option>
                <el-option label="西餐" value="西餐"></el-option>
                <el-option label="饮品" value="饮品"></el-option>
                <!-- 可以继续添加更多的菜品类型 -->
              </el-select>
            </el-form-item>
            <div>
              <el-form-item prop="mlicense" label="营业执照">
                <input type="file"  accept="image/*" />
              </el-form-item>
            </div>
          </div>
          <div class="you2">
            <button @click="submitRegisterForm">注册</button>
          </div>
        </el-form>

      </div>
      <div :class="active === 1? 'card' : 'card active'">
        <div class="head">
          <div class="name">智慧<span>校园</span></div>
        </div>
        <div class="desc"></div>
        <div class="btn">
          {{ active === 1? '新用户?' : '已有账号'}}
          <button @click="active = (active === 1)? 2 : 1">
            {{ active === 1? '去注册?' : '去登录'}}
          </button>
        </div>
      </div>

    </div>
  </div>
</template>

<script setup>
import { reactive, ref,onMounted} from "vue";
import router from "@/router";
import request from '@/utils/amusement'
import { ElMessage } from 'element-plus';
import axios from 'axios';
let active = ref(1)
const loginFormRef = ref()
// 表单的数据模型
const loginForm = reactive({
  username: '',
  password: ''
})
let merchantLoginForm = reactive({
  mname: '',
  mpassword: '',
  confirmPass: '',
  mphone:'',
  mphotourl:'',
  canteen:'',
  mlicense:'',
  mrange:''
});
// 表单的校验规则
const loginRules = reactive({
  username: [
    { required: true, message: '必须填入账号', trigger: 'blur' },
    { min: 3, max: 14, message: '长度应在 3-14 之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '必须填入密码', trigger: 'blur' },
    { pattern: /^(?![0-9]+$)(?! [a-zA-Z]+$)[0-9A-Za-z]{6,}$/,
      message: '密码长度为 6-12 位的数字和字母组成',
      trigger: 'blur'
    }
  ],
  validCode: [
    { required: true, message: '必须填入验证码', trigger: 'blur' }
  ]
})

const submitForm = () => {
  loginFormRef.value.validate((valid) => {
    if (valid) {
      request({
        url: '/all2/login2',
        method: 'post',
        data: loginForm // 确保这里是对象而不是 params
      }).then(res => {
        console.log(res)
        if (200 == res.data.errorCode) {
          const role = res.data.role;
          const message = res.data.msg;
          sessionStorage.setItem('role', role);  // 在这里添加存储 role 的代码
          sessionStorage.setItem('loginUser', JSON.stringify(res.data.data))
          if (role === 'admin') {
            ElMessage({
              message: message,
              type: 'success',
            });
            // 使用 window.location.href 进行跨端口跳转
            window.location.href = 'http://localhost:8081/#/';
          } else if (role === 'student') {
            ElMessage({
              message: message,
              type: 'success',
            });
            router.push('/home');
          } else if (role === 'mall') {
            ElMessage({
              message: message,
              type: 'success',
            });
            router.push('/home/mall/work');
          } else if (role === 'teacher') {
            ElMessage({
              message: message,
              type: 'success',
            });
            router.push('/teacher');
          }
          else if (role === 'freshman') {
            ElMessage({
              message: message,
              type: 'success',
            });
            router.push('/home');
          }else {
            ElMessage({
              message: '未知角色',
              type: 'error',
            });
            router.push('/'); // 如果角色未知，重定向到登录页
          }
        } else {
          ElMessage({
            message: '登录失败！',
            type: 'error',
          })
        }
      }).catch(error => {
        console.error("请求失败:", error);
        ElMessage({
          message: '请求失败，请稍后再试！',
          type: 'error',
        })
      })
    } else {
      ElMessage({
        message: '账号或者密码格式错误！',
        type: 'error',
      })
    }
  })
}
const isLogin = ref(true)
const registerFormRef = ref()
const registerRules = reactive({
  mname: [
    { required: true, message: '必须填写账号', trigger: 'blur' },
    { min: 3, max: 20, message: '账号长度为3-20', trigger: 'blur' },
  ],
  mpassword: [
    { required: true, message: '必须填写密码', trigger: 'blur' },
    { pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}$/, message: '密码必须是数字和字母相结合，长度至少6位！', trigger: 'blur' },
  ],
  confirmPass: [
    { required: true, message: '必须确认密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value !== merchantLoginForm.mpassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, trigger: 'blur' }
  ],
  mphone: [
    { required: true, message: '必须填写手机号', trigger: 'blur' },
    {
      pattern: /^(?:13[3-9]|14[5-9]|15[0-3]|15[5-9]|16[6]|17[3]|18[2-9]|19[3-9])[0-9]{8}$/,
      message: '格式不正确，请输入有效的手机号',
      trigger: 'blur'
    }
  ],
  canteen: [
    { required: true, message: '请选择食堂', trigger: 'change' }
  ]/*,
  mphotourl: [
    { required: true, message: '请上传营业执照', trigger: 'change' }
  ]*/
})
const fileUploaded = ref(false);
const submitRegisterForm = () => {
  registerFormRef.value.validate((valid) => {
    if (valid) {
      const formData = new FormData();
      formData.append('mname', merchantLoginForm.mname);
      formData.append('mpassword', merchantLoginForm.mpassword);
      formData.append('mphone', merchantLoginForm.mphone);
      formData.append('canteen', merchantLoginForm.canteen);
      formData.append('mrange', merchantLoginForm.mrange);
      const file = document.querySelector('input[type="file"]').files[0];
      if (file) {
        formData.append('userphoto', file);
      }
      axios({
        url: 'http://localhost:8085/file/addWithPhoto',
        method: 'POST',
        data: formData,
      }).then(response => {
        console.log('Response:', response);
        if (response.data.errorCode === 200) {
          ElMessage({
            message: '注册成功,请等待审核！',
            type: 'success',
          });
          toggleForm();
          router.push('/');
        } else {
          ElMessage({
            message: '账号存在！',
            type: 'error',
          });
        }
      }).catch(error => {
        console.log('Error:', error);
        console.log('Error Config:', error.config);
        console.log('Error Request:', error.request);
        ElMessage({
          message: '上传出错，请稍后再试！',
          type: 'error',
        });
      });
    } else {
      ElMessage({
        message: '账号或者密码格式错误！',
        type: 'error',
      });
    }
  });
};
const toggleForm = () => {
  isLogin.value = !isLogin.value
  if (isLogin.value) {
    merchantLoginForm.mname = ''
    merchantLoginForm.mpassword = ''
    merchantLoginForm.confirmPass = ''
    merchantLoginForm.mphone='',
        merchantLoginForm.mphotourl='',
        merchantLoginForm.canteen=''
    registerFormRef.value.resetFields()
  } else {
    merchantLoginForm.mname = ''
    merchantLoginForm.mpassword = ''
    merchantLoginForm.confirmPass = ''
    merchantLoginForm.mphone='',
        merchantLoginForm.mphotourl='',
        merchantLoginForm.canteen=''
    loginFormRef.value.resetFields()
  }
}
</script>
<style scoped>
.el-input{
  width: 370px;
  height: 40px;
}
.you{
  width: 330px;
}
.you1{
  padding-left: 50px;
}
.you2{
  padding-left: 50px;
}
.login-container {
  width: 100%;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url("../assets/imgs/loginback.jpeg") no-repeat center center;
  background-size: cover;
}
.login-container .slider{
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}
/*表的整体*/
.login-container .slider .form {
  width: 400px;
  height: 560px;
  background: #FFF8DC;
  backdrop-filter: blur(16px) saturate(0);
  border-radius: 10px;
  border: 1px solid rgba(255, 255, 255, 0.15);
  padding: 40px 60px;
  box-shadow:
      rgba(50, 50, 93, 0.25) 50px 50px 100px -20px,
      rgba(0, 0, 0, 0.5) 30px 30px 60px -30px,
      rgba(212, 217, 222, 0.35) 2px -2px 6px 0px inset;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: flex-start;
  margin: 0 10px;
  z-index: 3;
  transition: 0.5s ease-in-out;
}
.login-container  .form.hidden {
  height: 395px;
  box-shadow: none;
  z-index: 1;
}
.login-container .form .title{
  font-size: 20px;
  color: #696969;
  letter-spacing: 1px;
  font-weight: 300;
}
/*小字*/
.login-container .form .subtitle{
  font-size: 12px;
  color:  #696969;
  letter-spacing: 1px;
  margin-bottom: 35px;
}
.login-container .form .inputf{
  width: 95%;
  position: relative;
  margin-bottom: 35px;
}

.login-container .form .inputf el-input {
  width: 100%;
  height: 30px;
  border: none;
  outline: 1.5px solid  #696969;
  background: transparent;
  border-radius: 8px;
  font-size: 12px;
  padding: 0 15px;
  color:  #696969;
}
.login-container .form .inputf input::placeholder {
  color: rgb(175, 180, 190);
}
.login-container .form .inputf input:focus {
  outline: 1.5px solid #a9a9a9;
}
.login-container .form .inputf input:focus::placeholder {
  opacity: 0;
}

.login-container .form .inputf input:not(:placeholder-shown) + .label {
  opacity: 1;
  top: -20px;
}
.login-container .form .inputf .label{
  position: absolute;
  top:0;
  left: 0;
  color:  #696969;;
  font-size: 11px;
  font-weight: bold;
  transition: 0.25s ease-out;
  opacity: 0;
}
.login-container .form button{
  width: 30%;
  height: 35px;
  background: #afeeee;
  color: #ffffff;
  border: none;
  outline: none;
  border-radius: 5px;
  font-weight: bold;
  font-size: 12px;
  cursor: pointer;
}
.card {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translate(11%, -50%);
  width: 480px;
  height: 450px;
  background: url("../assets/imgs/loginfront.jpeg") white;
  background-size: contain;
  padding: 40px;
  border-radius: 0 10px 10px 0;
  transition: 0.5s ease-in-out;
  z-index: 2;
}

.card.active {
  right: calc(100% - 440px);
  border-radius: 10px 0 0 10px;
}
.card .head{
  font-size: 34px;
  margin-bottom: 35px;
}
.card .head .name{
  font-weight: 300;
}
.card .head .name span{
  color: #afeeee;
  font-weight: bold;
}
.card .desc{
  font-size: 14px;
  text-align: justify;
  margin-bottom: 35px;

}
.btn{
  font-size: 14px;
  margin-top: 380px;
}
.btn button{
  background: #afeeee;
  font-size: 14px;
  padding: 5px 15px;
  border: none;
  outline: none;
  border-radius: 5px;
  cursor: pointer;
  margin-left: 10px;
}

</style>